from wtforms import StringField
from wtforms.validators import ValidationError, Length, DataRequired
from IPy import IP

from app.form.base_form import BaseForm
from app.common.enums import IpFilterType
from app.models import IpFilter


class IpFilterForm(BaseForm):
    """IP过滤器表单验证
    """
    id = StringField("记录ID")
    network_segment = StringField(validators=[
        DataRequired('Ip网段不能为空'),
        Length(8, 20, "Ip网段8~20个字符")
    ])
    description = StringField(validators=[
        Length(max=255, message="描述最多255个字符")
    ])

    # 判断过滤类型
    def validate_filter_type(self, field):
        type_dict = IpFilterType._value2member_map_
        if int(field.data) not in type_dict:
            raise ValidationError(message="过滤类型不存在")

    # 判断Ip网段是否已存在
    def validate_network_segment(self, field):
        # 验证网段格式是否正确
        try:
            IP(field.data)
        except ValueError:
            raise ValidationError(message="Ip网段格式不正确")
        # 查询数据库是否存在网段
        data = IpFilter.query.filter_by(network_segment=field.data).first()
        # 如果传入的id存在，就判断是否是原来的值
        id = self.id.data
        if id is not None:
            if data is not None and not data.id == id:
                raise ValidationError(message="Ip网段已存在")
        else:  # 没传入id，添加操作，只需要判断是否存在记录
            if data is not None:
                raise ValidationError(message="Ip网段已存在")
